package com.lanchetech.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.fsg.uid.UidGenerator;
import com.lanchetech.admin.service.OrderService;
import com.lanchetech.admin.service.ProductService;
import com.lanchetech.admin.service.ShopService;
import com.lanchetech.admin.service.UserService;
import com.lanchetech.bean.dto.DeleteRuleDTO;
import com.lanchetech.bean.dto.EditRuleDTO;
import com.lanchetech.bean.dto.KickingRuleDTO;
import com.lanchetech.bean.dto.ProjectDTO;
import com.lanchetech.bean.request.*;
import com.lanchetech.bean.response.*;
import com.lanchetech.bean.vo.InvoiceApplyNuonuoDetailVO;
import com.lanchetech.bean.vo.InvoiceApplyNuonuoVO;
import com.lanchetech.bean.vo.OrderSkuVO;
import com.lanchetech.common.enums.*;
import com.lanchetech.common.util.HttpUtil;
import com.lanchetech.common.util.StringHelper;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import nuonuo.open.sdk.NNOpenSDK;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.lanchetech.common.constants.JypConstant.HIPO_USER_ID;

@Api(value = "测试接口", tags = "测试接口")
@RequestMapping("/api/test")
@RestController
public class TestController {

    @Autowired
    ProductService productService;

    @Autowired
    UserCommissionMapper userCommissionMapper;

    @Autowired
    CommissionService commissionService;

    @Autowired
    IdentityMapper identityMapper;

    @Autowired
    UserRelationshipMapper userRelationshipMapper;

    @Autowired
    BonusCountMapper bonusCountMapper;

    @Autowired
    InvoiceApplyMapper invoiceApplyMapper;

    @Autowired
    OrderService orderService;

    @Autowired
    InvoiceAccountMapper invoiceAccountMapper;

    @Autowired
    AgoraService agoraService;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    ShopService shopService;

    @Autowired
    ShopStatisticsMapper shopStatisticsMapper;

    @Autowired
    UserService userService;

    @Autowired
    LogisticsService logisticsService;

    @Autowired
    JpushService jpushService;

    @Autowired
    UserGroupMapper userGroupMapper;

    @Autowired
    SkuMapper skuMapper;

    @Autowired
    FlashSaleSkuMapper flashSaleSkuMapper;

    @Autowired
    FlashSaleActivityMapper flashSaleActivityMapper;

    @Autowired
    CoinDeductionMapper coinDeductionMapper;

    @Autowired
    FreightMapper freightMapper;

    @Autowired
    FreightListMapper freightListMapper;

    @Autowired
    OrdersMapper ordersMapper;

    @Autowired
    OrderSkuMapper orderSkuMapper;

    @Autowired
    UserAddressMapper userAddressMapper;

    @Autowired
    OrderAddressMapper orderAddressMapper;


    @Resource
    UidGenerator uidGenerator;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    SpuMapper spuMapper;

    @Autowired
    OrderCommentMapper orderCommentMapper;

    @Autowired
    AfterSaleMapper afterSaleMapper;

    @Autowired
    OrderDiscountMapper orderDiscountMapper;

    @Autowired
    CommentStatisticsMapper commentStatisticsMapper;

    @Autowired
    FlashSaleSpuMapper flashSaleSpuMapper;

    @Autowired
    DaoService daoService;

    @Autowired
    PrivilegeMapper privilegeMapper;

    @Autowired
    SpuCommissionMapper spuCommissionMapper;

    @Autowired
    PackagesMapper packagesMapper;

    @Autowired
    PackageSkuMapper packageSkuMapper;

    @Autowired
    UserCouponMapper userCouponMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    CoinSettingMapper coinSettingMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    CoinRewardMapper coinRewardMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    SkuColumnCourseMapper skuColumnCourseMapper;

    @Autowired
    ColumnCourseAuthMapper columnCourseAuthMapper;

    @Autowired
    ConsumptionService consumptionService;

    @Autowired
    CoinFlowMapper coinFlowMapper;

    @Autowired
    ExpService expService;

    @Autowired
    HipoConfigMapper hipoConfigMapper;

    @Autowired
    LevelService levelService;

    @Autowired
    CardFlowMapper cardFlowMapper;

    @Autowired
    AppointmentSettingMapper appointmentSettingMapper;

    @Autowired
    UserVoucherMapper userVoucherMapper;

    @Autowired
    BossMapper bossMapper;

    @Autowired
    BargainRecordMapper bargainRecordMapper;

    @Autowired
    BargainSkuMapper bargainSkuMapper;

    @Autowired
    BargainSpuMapper bargainSpuMapper;

    @Autowired
    BargainActivityMapper bargainActivityMapper;

    @Autowired
    SecondRelationshipMapper secondRelationshipMapper;

    @Autowired
    ShopRelationshipMapper shopRelationshipMapper;

    @Autowired
    CommonFarmService commonFarmService;

    @Autowired
    SmsService smsService;

    @Autowired
    OrderPayMapper orderPayMapper;

    @Autowired
    TenantMapper tenantMapper;

    @Autowired
    TenantFlowMapper tenantFlowMapper;

    @Autowired
    private Scheduler scheduler;

    @Autowired
    FinanceService financeService;

    @Autowired
    CommonOrderService commonOrderService;

    @Autowired
    QuartzService quartzService;

    @Autowired
    ShopAnnouncementMapper shopAnnouncementMapper;

    @Autowired
    AnnouncementMapper announcementMapper;

    @Autowired
    AnnouncementService announcementService;

    @Autowired
    KuaidizsService kuaidizsService;

    @ApiOperation("更新所有userGroup的上级运营中心")
    @GetMapping("/updateUserGroupShareholder")
    public BaseResp updateUserGroupShareholder() {
        List<UserGroup> userGroupList = userGroupMapper.findAllByCaptainIdEqualShareholderId();

        for (UserGroup item : userGroupList) {
            // 1、当前上级是运营中心
//            Identity identity1 = identityMapper.findOneByUserId(item.getCaptainId());
//            if (identity1 != null && identity1.getShareholderLevel() >= UserLevelEnum.SHAREHOLDER_L1.getLevel()) {
//                userGroupMapper.updateShareholderIdById(identity1.getUserId(), item.getId());
//                continue;
//            }

            // 2、当前上级不是运营中心，则寻找当前上级无限邀请上级
            Long superId = getSuper(item.getCaptainId());
            if (superId != null) {
                userGroupMapper.updateShareholderIdById(superId, item.getId());
                continue;
            }

            // 3、获取当前上级所在团队是否有运营中心
            List<UserGroup> userGroupList1 = userGroupMapper.findAllByMemberId(item.getCaptainId());
            if (!userGroupList1.isEmpty() && userGroupList1.get(0).getShareholderId() > 0) {
                Identity identity2 = identityMapper.findOneByUserId(userGroupList1.get(0).getShareholderId());
                if (identity2 != null && identity2.getShareholderLevel() >= UserLevelEnum.SHAREHOLDER_L1.getLevel()) {
                    userGroupMapper.updateShareholderIdById(identity2.getUserId(), item.getId());
                    continue;
                }
            }

            // 4、算到平台头上
            userGroupMapper.updateShareholderIdById(HIPO_USER_ID, item.getId());
        }
        return new BaseResp();
    }

    private UserCommission build(Long superiorId, Long subordinateId, BigDecimal amount, UserCommissionTypeEnum typeEnum, Calendar calendar, BigDecimal performance, Byte identityType, Long orderSkuId, String remark, Byte fromType) {

        // 记录团队业绩
        UserGroup userGroup = userGroupMapper.findOneByCaptainIdAndMemberId(superiorId, subordinateId);
        if (userGroup != null) {
            userGroup.setOrderCount(userGroup.getOrderCount() + 1);
            userGroup.setAmount(userGroup.getAmount().add(performance));
            userGroup.setCommission(userGroup.getCommission().add(amount));
            userGroupMapper.updateByPrimaryKeySelective(userGroup);
        }

        return UserCommission.builder()
                .superiorId(superiorId)
                .subordinateId(subordinateId)
                .commission(amount)
                .type(typeEnum.getType())
                .freezeTime(calendar.getTime())
                .status(UserCommissionStatusEnum.FREEZE.getStatus())
                .createdAt(new Date())
                .updatedAt(new Date())
                .amount(performance)
                .identityType(identityType)
                .businessType(UserCommissionBusinessTypeEnum.USER.getType())
                .orderSkuId(orderSkuId)
                .remark(remark)
                .build();
    }

    @ApiOperation("给张帅补单")
    @GetMapping("/createCommission")
    public BaseResp createCommission() {

//        UserCommissionTypeEnum.SHAREHOLDER_SHARE_COMMISSION : UserCommissionTypeEnum.SHAREHOLDER_GROUP_COMMISSION
        List<UserCommission> userCommissionList = userCommissionMapper.findAllByTypeAndCreatedAt(UserCommissionTypeEnum.SHAREHOLDER_SHARE_COMMISSION.getType());
        List<UserCommission> userCommissionList2 = userCommissionMapper.findAllByTypeAndCreatedAt(UserCommissionTypeEnum.SHAREHOLDER_GROUP_COMMISSION.getType());
        userCommissionList.addAll(userCommissionList2);


        userCommissionList.stream().forEach(item -> {
            List<UserGroup> userGroupList1 = userGroupMapper.findAllByMemberId(item.getSuperiorId());
            // 设置冻结时间
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 7);

            if (!userGroupList1.isEmpty()) {
                if (userGroupList1.get(0).getShareholderId() == 41731) {
                    // 看看这笔这个上级有没有拿到服务奖
                    if (userCommissionMapper.findOneByOrderSkuIdAndType(item.getOrderSkuId(), UserCommissionTypeEnum.SHAREHOLDER_GROUP_COMMISSION.getType()) == null) {
                        System.out.println(item.getOrderSkuId());
                        // 给张帅发
//                        BigDecimal fromShareholderCommission = item.getCommission().multiply(daoService.getHipoConfigNumber(HipoConfigEnum.SHAREHOLDER_GET_FROM_SHAREHOLDER_SALE.getConfig())).setScale(2, BigDecimal.ROUND_HALF_UP);
//                        userCommissionMapper.insert(build(41731L, item.getSuperiorId(), fromShareholderCommission, UserCommissionTypeEnum.SHAREHOLDER_GET_FROM_SHAREHOLDER_SALE, calendar, item.getCommission(), IdentityTypeEnum.SHAREHOLDER.getType(), item.getId(), item.getRemark(), item.getRemark().contains("运营中心") ? IdentityTypeEnum.SHAREHOLDER.getType() : IdentityTypeEnum.MEMBER.getType()));
                    }
                }
            }
        });
        return new BaseResp();
    }


    public Long getSuper(Long subId) {
        UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(subId);
        if (userRelationship != null) {
            Identity identity = identityMapper.findOneByUserId(userRelationship.getSuperiorId());
            if (identity != null && identity.getShareholderLevel() >= UserLevelEnum.SHAREHOLDER_L1.getLevel()) {
                return identity.getUserId();
            } else {
                // 继续找上级的上级
                return getSuper(userRelationship.getSuperiorId());
            }
        }
        return null;
    }


    @ApiOperation("补单")
    @GetMapping("/retryCompleteOrder")
    public BaseResp retryCompleteOrder() {
        String tradeNo = "";
        if (tradeNo.length() == 0) {
            return new BaseResp(ResultCode.FAIL);
        }
        Orders orders = ordersMapper.findOneByTradeNo(tradeNo);

        //更新店铺统计数据
        List<Orders> userOrders = ordersMapper.findAllByUserIdAndShopId(orders.getUserId(), orders.getShopId());
        shopStatisticsMapper.updateCompletePay(ShopStatistics.builder()
                .shopId(orders.getShopId())
                .orderAmount(orders.getTotalPayAmount())
                .customCount(userOrders.size() > 1 ? 0L : 1L)
                .updatedAt(new Date())
                .build());

        // 更新订单状态和支付时间
        ordersMapper.updateStatusAndPayTimeByTradeNo(OrdersStatusEnum.PAID.getStatus(), new Date(), tradeNo);
        orderSkuMapper.updateStatusByOrderId(OrdersStatusEnum.PAID.getStatus(), orders.getId());

        // 更新优惠明细状态
        orderDiscountMapper.updateStatusAndUpdatedAtByOrderId(UseEnum.USED.getStatus(), new Date(), orders.getId());

        // 如果是代付，则更新代付状态
        if (PayTypeEnum.ANOTHER_APY.getType().equals(orders.getPayType())) {
            orderPayMapper.updateStatusAndUpdatedAtByTradeNo(OrderPayStatusEnum.PAID.getStatus(), new Date(), orders.getTradeNo());
        }

        // 将此订单中使用的优惠券，状态变更; 将此订单的使用的积分从个人积分余额中扣除;
        List<OrderDiscount> orderDiscountList = orderDiscountMapper.findAllByOrderId(orders.getId());
        if (!CollectionUtils.isEmpty(orderDiscountList)) {
            for (OrderDiscount item : orderDiscountList) {
                if (PromotionEnum.COUPON.getPromotion().equals(item.getType())) {
                    userCouponMapper.updateStatusAndUpdatedAtByUserIdAndCouponId(UseEnum.USED.getStatus(), new Date(), orders.getUserId(), item.getRelateId());
                }
                if (PromotionEnum.COIN_USE.getPromotion().equals(item.getType())) {
                    User user = userMapper.selectByPrimaryKey(orders.getUserId());
                    userMapper.updateCoinById(user.getCoin().subtract(item.getDiscountAmount()), user.getId());

                    // 创建积分使用记录
                    coinFlowMapper.insert(CoinFlow.builder()
                            .userId(user.getId())
                            .amount(item.getDiscountAmount())
                            .tradeType(CoinFlowTradeTypeEnum.CONSUME.getTradeType())
                            .type(CoinFlowTradeTypeEnum.CONSUME.getType())
                            .coin(user.getCoin().subtract(item.getDiscountAmount()))
                            .relateId(item.getOrderId())
                            .remark("支付订单使用积分优惠")
                            .createdAt(new Date())
                            .build());
                }
            }
        }

        User user = userMapper.selectByPrimaryKey(orders.getUserId());

        // 支付成功了，就增加sku, spu销量数量
        // 减少sku库存
        List<OrderSkuVO> orderSkuVOList = orderSkuMapper.findAllByOrderId(orders.getId());
        Map<Long, Integer> spuCountMap = new HashMap<>();
        orderSkuVOList.stream().forEach(item -> {
            spuCountMap.put(item.getSpuId(), spuCountMap.containsKey(item.getSpuId()) ? spuCountMap.get(item.getSpuId()) + item.getCount() : item.getCount());
            skuMapper.updateStockAndSalesById(item.getCount(), item.getSkuId());
            // 如果商品参加了活动，则更新活动库存
            // 限时优惠
            if (ActivityEnum.FLASH_SALE.getActivity().equals(item.getActivityType())) {
                flashSaleSkuMapper.updateStockAndSalesByActivityIdAndSkuId(item.getCount(), item.getActivityId(), item.getSkuId());

                // 如果是线上自提，则发放秒杀兑换卡
                if (OrderTypeEnum.ONLINE_SELF.getType().equals(item.getOrderType())) {
                    for (int i = 0; i < item.getCount(); i++) {
                        userVoucherMapper.insert(UserVoucher.builder()
                                .userId(item.getUserId())
                                .fromOrderSkuId(item.getId())
                                .productName(item.getProductName())
                                .shopId(item.getShopId())
                                .spuId(item.getSpuId())
                                .type(VoucherTypeEnum.FLASH_SALE.getType())
                                .status(VoucherStatusEnum.AVAILABLE.getStatus())
                                .createdAt(new Date())
                                .updatedAt(new Date())
                                .build());
                    }
                }
            }

            // 砍价
            if (ActivityEnum.BARGAIN.getActivity().equals(item.getActivityType())) {
                bargainSkuMapper.updateStockAndSalesByActivityIdAndSkuId(item.getCount(), item.getActivityId(), item.getSkuId());

                // 发放秒杀兑换卡
                if (OrderTypeEnum.ONLINE_SELF.getType().equals(item.getOrderType())) {
                    for (int i = 0; i < item.getCount(); i++) {
                        userVoucherMapper.insert(UserVoucher.builder()
                                .userId(item.getUserId())
                                .fromOrderSkuId(item.getId())
                                .productName(item.getProductName())
                                .shopId(item.getShopId())
                                .spuId(item.getSpuId())
                                .type(VoucherTypeEnum.BARGAIN.getType())
                                .status(VoucherStatusEnum.AVAILABLE.getStatus())
                                .createdAt(new Date())
                                .updatedAt(new Date())
                                .build());
                    }
                }
            }

            if (OrderTypeEnum.ONLINE_SELF.getType().equals(item.getOrderType())) {
                // 农场任务
                boolean done = commonFarmService.checkTaskDone(user, FarmTaskKindEnum.TARGET_SHOP_SPU.getKind(), item.getSpuId(), Long.valueOf(item.getCount()));
                if (!done) {
                    commonFarmService.checkTaskDone(user, FarmTaskKindEnum.ALL_SHOP_SPU.getKind(), item.getSpuId(), Long.valueOf(item.getCount()));
                }
            }
        });


        for (Map.Entry<Long, Integer> item : spuCountMap.entrySet()) {
            spuMapper.updateSalesById(item.getValue(), item.getKey());
        }

        // 发放积分奖励
        if (!PayTypeEnum.EXCHANGE_CARD.getType().equals(orders.getPayType())) {

            // 发放嗨跑佣金
            commissionService.prepareHipoCommission(orderSkuVOList);

            // 创建消费记录
            consumptionService.updateConsumptionAmount(ConsumptionRecord.builder()
                    .userId(orders.getUserId())
                    .amount(orders.getTotalPayAmount())
                    .recordType(ConsumptionRecordTypeEnum.CONSUMPTION.getRecordType())
                    .relateId(orders.getId())
                    .remark(StringHelper.subPayBodyString(orderSkuVOList.get(0).getProductName()) + (orderSkuVOList.size() > 1 ? "等" + orderSkuVOList.size() + "件商品" : ""))
                    .build());
        }

        // 如果是商家自提订单，则发钱给商家(兑换卡类型的，销售时就发钱，兑换时就不要重复发钱)
        if (!PayTypeEnum.EXCHANGE_CARD.getType().equals(orders.getPayType())) {

            Shop shop = shopMapper.selectByPrimaryKey(orders.getShopId());
            if (orders.getTotalPayAmount().compareTo(BigDecimal.ZERO) > 0) {
                // 每个订单里最多只能有1个商品

                // 立即发放商品销售收入给商户
                Tenant tenant = tenantMapper.selectByPrimaryKey(shop.getId());
                tenantFlowMapper.insert(TenantFlow.builder()
                        .amount(orders.getTotalTenantAmount())
                        .tradeType(TenantTradeTypeEnum.PRODUCT.getTradeType())
                        .type(TenantTradeTypeEnum.PRODUCT.getType())
                        .point(tenant.getPoint().add(orders.getTotalTenantAmount()))
                        .relateId(orders.getId())
                        .remark(orderSkuVOList.get(0).getProductName())
                        .createdAt(new Date())
                        .tenantId(tenant.getId())
                        .build());
                tenantMapper.updatePointById(tenant.getPoint().add(orders.getTotalTenantAmount()), tenant.getId());
                financeService.createFreezeAmount(orders, orders.getTotalTenantAmount(), FreezeTypeEnum.ORDERS.getType());

                // 如果商家有推荐人，则发商家推荐佣金
//                    BigDecimal rate = daoService.getHipoConfigNumber(HipoConfigEnum.SHOP_RECOMMEND_BONUS_RATE.getConfig());
//                    if (rate.compareTo(BigDecimal.ZERO) > 0) {
//                        ShopRelationship shopRelationship = shopRelationshipMapper.findOneByShopId(orders.getShopId());
//
//                        if (shopRelationship != null) {
//                            userCommissionMapper.insert(UserCommission.builder()
//                                    .superiorId(shopRelationship.getId())
//                                    .subordinateId(orders.getUserId())
//                                    .orderSkuId(orderSkuVOList.get(0).getId())
//                                    .commission(orders.getTotalPayAmount().multiply(rate).setScale(2, BigDecimal.ROUND_HALF_DOWN))
//                                    .remark(orderSkuVOList.get(0).getProductName())
//                                    .relateId(orders.getId())
//                                    .type(UserCommissionTypeEnum.SHOP_RECOMMEND_BONUS.getType())
//                                    .freezeTime(calendar.getTime())
//                                    .status(UserCommissionStatusEnum.FREEZE.getStatus())
//                                    .createdAt(new Date())
//                                    .updatedAt(new Date())
//                                    .amount(orders.getTotalPayAmount())
//                                    .identityType((byte) -1)
//                                    .businessType(UserCommissionBusinessTypeEnum.USER.getType())
//                                    .shopId(orders.getShopId())
//                                    .build());
//                        }
//                    }
            }
        }

        TriggerKey triggerKey = TriggerKey.triggerKey("ORDER_PAY_TRIGGER" + orders.getId().toString(), "WAIT_PAY");
        JobKey jobKey = JobKey.jobKey("WAIT_PAY_JOB" + orders.getId().toString(), "WAIT_PAY");
        try {
            //关闭定时任务
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器中的任务
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        //编辑商户通知消息
        announcementService.sendOrderAnnouncement(orders);

        //修改快递助手中的订单状态
        Shop shop = shopMapper.selectByPrimaryKey(orders.getTenantId());
        return new BaseResp();
    }


    @ApiOperation("批量创建商户")
    @GetMapping("/batchCreateShop")
    public BaseResp batchCreateShop() {
        List<Shop> shopList = shopMapper.findAll();

        shopList.stream().forEach(item -> {
            //新建商店统计数据表
            shopStatisticsMapper.insert(ShopStatistics.builder()
                    .shopId(item.getId())
                    .orderAmount(BigDecimal.ZERO)
                    .orderCount(0L)
                    .customCount(0L)
                    .visitCount(0L)
                    .viewCount(0L)
                    .createdAt(new Date())
                    .updatedAt(new Date())
                    .build());
            shopService.createTenant(item);
        });
        return new BaseResp();
    }

    @ApiOperation("发票测试")
    @PostMapping("/test1")
    public JSONObject auditInvoiceApply(@RequestBody InvoiceApply invoiceApply) {
//        JSONObject jsonObject = getInvoice("21081514034801246091");
        JSONObject result = applyInvoice(invoiceApply);
        //  开具发票之后，不能立马得到结果，所有需要过一段时间再获取
        if (result.getString("code").equals("E0000")) {
            getInvoice(JSONObject.parseObject(result.getString("result")).getString("invoiceSerialNum"), invoiceApply);
        }
        return result;

    }

    final static String taxnum = "339901999999824";
    final static String appKey = "SD72441645";
    final static String appSecret = "SDA75B8DDA6A47A6";
    final static String token = "我是token";
    final static String url = "https://sandbox.nuonuocs.cn/open/v1/services";

    public JSONObject applyInvoice(InvoiceApply invoiceApply) {
        NNOpenSDK nnsdk = NNOpenSDK.getIntance();
        String method = "nuonuo.ElectronInvoice.requestBillingNew";

        // 获取购买商品信息
        OrderResp orderDetail = orderService.getOrderDetail(invoiceApply.getOrderId()).getValue();

        List<InvoiceApplyNuonuoDetailVO> invoiceDetailList = new ArrayList<>();
        if (invoiceApply.getContentType() == 0) {
            orderDetail.getOrderSkuList().stream().forEach(item -> {
                invoiceDetailList.add(InvoiceApplyNuonuoDetailVO.builder()
                        .goodsName(item.getProductName())
                        .price(String.valueOf(item.getPrice()))
                        .num(String.valueOf(item.getCount()))
                        .taxRate("0.13")
                        .withTaxFlag("1")
                        .build());
            });
        } else {
            invoiceDetailList.add(InvoiceApplyNuonuoDetailVO.builder()
                    .goodsName("商品类别")
                    .taxRate("0.13")
                    .tax(String.valueOf(orderDetail.getTotalPayAmount().divide(new BigDecimal("1.13")).multiply(new BigDecimal(0.13))))
                    .taxExcludedAmount(String.valueOf(orderDetail.getTotalPayAmount().divide(new BigDecimal("1.13"))))
                    .taxIncludedAmount(String.valueOf(orderDetail.getTotalPayAmount()))
                    .withTaxFlag("1")
                    .build());
        }

        // 填写发票信息
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        InvoiceAccount invoiceAccount = invoiceAccountMapper.selectByPrimaryKey(invoiceApply.getInvoiceAccountId());

        InvoiceApplyNuonuoVO order = InvoiceApplyNuonuoVO.builder()
                .buyerName(invoiceAccount.getTitle())
                .buyerTaxNum(invoiceAccount.getTaxNumber())
                .buyerAddress(invoiceAccount.getAddress())
                .buyerAccount(invoiceAccount.getOpenBank() + " " + invoiceAccount.getBankAccount())
                .salerTaxNum(taxnum)
                .salerTel("1782222") // TODO
                .salerAddress("浙江杭州")
                .orderNo(String.valueOf(orderDetail.getId()))
                .invoiceDate(sdf.format(new Date()))
                .clerk("张三") // TODO
                .pushMode("1") // 推送方式：-1,不推送;0,邮箱;1,手机（默认* ）;2,邮箱、手机
                .buyerPhone(invoiceAccount.getPhone())
                .email(invoiceAccount.getEmail())
                .invoiceType("1")
                .invoiceDetail(invoiceDetailList)
                .build();

        if (invoiceAccount.getInvoiceType().equals(InvoiceTypeEnum.S.getType())) {
            order.setInvoiceLine("s");
        }

        String content = nnsdk.convertToUtf8("{\"order\":" + JSONObject.toJSONString(order) + "}");
        String senid = UUID.randomUUID().toString().replace("-", "");

        String result = nnsdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);
        JSONObject newresult = JSONObject.parseObject(result);
        return newresult;
    }

    @Async
    public void getInvoice(String invoiceSerialNum, InvoiceApply invoiceApply) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        NNOpenSDK nnsdk = NNOpenSDK.getIntance();
        String method = "nuonuo.ElectronInvoice.queryInvoiceResult";

        String content = "{\"orderNos\": [],\"serialNos\": [\"" + invoiceSerialNum + "\"] }";
        String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，32位随机码，无需修改，保持默认即可
        String result = nnsdk.sendPostSyncRequest(url, senid, appKey, appSecret, token, taxnum, method, content);

        JSONObject newResult = JSONObject.parseObject(result);

        JSONArray eventInfoData = (JSONArray) newResult.get("result");
        JSONObject jsonArray = eventInfoData.getJSONObject(0);

        invoiceApply.setSerialNo(jsonArray.getString("serialNo"));
        invoiceApply.setFileUrl(jsonArray.getString("pdfUrl"));
        invoiceApply.setStatus(InvoiceStatusEnum.DONE.getStatus());

        invoiceApply.setDealTime(new Date());
        invoiceApplyMapper.updateStatusAndDealTimeAndFileUrlById(invoiceApply);
    }


    @ApiOperation("获取用量")
    @GetMapping("/getUsage")
    public ResultData<UsageResp> getUsage() {
        return new ResultData<>(agoraService.getUsageList("Ks1c4fxe8", "2021-11-11", "2021-11-14", "default"));
    }

    @ApiOperation("创建封禁规则")
    @PostMapping("/createKickingRule")
    public BaseResp createKickingRule(@RequestBody KickingRuleDTO req) {
        agoraService.createKickingRule(req);
        return new BaseResp();
    }


    @ApiOperation("获取封禁规则列表")
    @GetMapping("/getKickingRule")
    public BaseResp getKickingRule(@RequestParam("appId") String appId) {
        agoraService.getKickingRule(appId);
        return new BaseResp();
    }

    @ApiOperation("更新封禁用户权限规则的生效时间")
    @PostMapping("/editKickingRule")
    public BaseResp editKickingRule(@RequestBody EditRuleDTO dto) {
        agoraService.editKickingRule(dto);
        return new BaseResp();
    }

    @ApiOperation("删除封禁用户权限规则")
    @PostMapping("/deleteKickingRule")
    public BaseResp deleteKickingRule(@RequestBody DeleteRuleDTO dto) {
        agoraService.deleteKickingRule(dto);
        return new BaseResp();
    }

    @ApiOperation("查询用户状态")
    @GetMapping("/getUserStatus")
    public BaseResp getUserStatus(@RequestParam("appId") String appid, @RequestParam("uid") Long uid, @RequestParam("channelName") String channelName) {
        agoraService.getUserStatus(appid, uid, channelName);
        return new BaseResp();
    }

    @ApiOperation("获取用户列表")
    @GetMapping("/getChannelUser")
    public BaseResp getChannelUser(@RequestParam("appId") String appid, @RequestParam("channelName") String channelName) {
        agoraService.getChannelUser(appid, channelName);
        return new BaseResp();
    }


    @ApiOperation("获取频道分页")
    @GetMapping("/getChannelPage")
    public BaseResp getChannelPage(@RequestParam("id") Long id) {
        getSuperiorShareholder(id);
        return new BaseResp();
    }

    public Long getSuperiorShareholder(Long subordinateId) {
        Map<Long, Boolean> map = new HashMap<>();
        Long sub = subordinateId;
        Long superiorId = null;
        do {
            // 如果已经存在，说明进入循环了
            if (!map.containsKey(sub)) {
                map.put(sub, true);
                System.out.println(sub);
                UserRelationship userRelationship = userRelationshipMapper.findOneBySubordinateId(sub);
                if (userRelationship != null) {
                    Identity superIdentity = identityMapper.findOneByUserId(userRelationship.getSuperiorId());
                    if (superIdentity != null && superIdentity.getShareholderLevel() >= UserLevelEnum.SHAREHOLDER_L1.getLevel()) {
                        superiorId = superIdentity.getUserId();
                    } else {
                        sub = userRelationship.getSuperiorId();
                    }
                } else {
                    superiorId = HIPO_USER_ID;
                }
            } else {
                superiorId = HIPO_USER_ID;
            }
        } while (superiorId == null);
        System.out.println("完成" + superiorId);
        return superiorId;
    }


    @ApiOperation("获取录制资源")
    @PostMapping("/getRecordingResources")
    public String getRecordingResources(@RequestBody RecordingResourcesReq req) {
        return agoraService.getRecordingResources(req);
    }

    @ApiOperation("开始录制测试")
    @PostMapping("/startRecord")
    public StartRecordResp startRecord(@RequestBody StartRecordReq req) {
        return agoraService.startRecord(req);
    }

    @ApiOperation("开始录制测试")
    @GetMapping("/startRecord2")
    public BaseResp startRecord2() {
        StartRecordResp startRecordResp = new StartRecordResp();
        String url = "https://api.agora.io/v1/apps/" + "8cc3e6be3564492d8cc8d84d11597eed" + "/cloud_recording/resourceid/" + "Etkl6g-zSB7EpP-Da1zN67YwvTMSua4-NafBHVviqfHJOnozffOAao5RnFCi1PbsoqBRqamzC2FOhWKarc4Os82n5PXQvL3YGBQFUTHw62gwQ1eZ191DnK6kKoLKbciMbCbONimzgPtfTCsWO6bf0gwScrGM6fk6ouXtFdLVeO2DHaliPLkpP9qg5F1cvh0fpQjEM8ZqsLQA1y2AdcVyj0uzKBSmVI9zQ8fqQk-bGZqzT4wMv4It0MW02zg_IjydUMCgkmkCspP-yHoYVZdv4QLul_QElhEfUFVD1db-X6ifyZr8nVUbXq-W_Sbz-xBQrN281k6Na2LddJPEyavctU3US592jQnq9b_0MLYNaNw" + "/mode/" + "individual" + "/start";
        String json = "{\n" +
                "        \"uid\": \"1234567\",\n" +
                "        \"cname\": \"httpClient\",\n" +
                "        \"clientRequest\": {\n" +
                "            \"recordingConfig\": {\n" +
                "                \"maxIdleTime\": 30,\n" +
                "                \"streamTypes\": 2,\n" +
                "                \"channelType\": 0,\n" +
                "                \"subscribeUidGroup\": 0\n" +
                "            },\n" +
                "            \"storageConfig\": {\n" +
                "                \"accessKey\": \"xxxxxxf\",\n" +
                "                \"region\": 3,\n" +
                "                \"bucket\": \"xxxxx\",\n" +
                "                \"secretKey\": \"xxxxx\",\n" +
                "                \"vendor\": 2,\n" +
                "                \"fileNamePrefix\": [\n" +
                "                    \"directory1\",\n" +
                "                    \"directory2\"\n" +
                "                ]\n" +
                "            }\n" +
                "        }\n" +
                "    }";
        try {
            String resp = HttpUtil.doPostWithHead(json, url, agoraService.getAuthorization());
            startRecordResp = JSON.parseObject(resp, StartRecordResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BaseResp();
    }


    @ApiOperation("结束录制测试")
    @GetMapping("/stopRecord2")
    public BaseResp stopRecord2() {

        String url = "https://api.agora.io/v1/apps/" + "8cc3e6be3564492d8cc8d84d11597eed" + "/cloud_recording/resourceid/" + "Etkl6g-zSB7EpP-Da1zN67YwvTMSua4-NafBHVviqfHJOnozffOAao5RnFCi1PbsoqBRqamzC2FOhWKarc4Os82n5PXQvL3YGBQFUTHw62gwQ1eZ191DnK6kKoLKbciMbCbONimzgPtfTCsWO6bf0gwScrGM6fk6ouXtFdLVeO2DHaliPLkpP9qg5F1cvh0fpQjEM8ZqsLQA1y2AdcVyj0uzKBSmVI9zQ8fqQk-bGZqzT4wMv4It0MW02zg_IjydUMCgkmkCspP-yHoYVZdv4QLul_QElhEfUFVD1db-X6ifyZr8nVUbXq-W_Sbz-xBQrN281k6Na2LddJPEyavctU3US592jQnq9b_0MLYNaNw" + "/sid/" + "c25b69c12043cbc6c3212c9fe9bdb81f" + "/mode/" + "individual" + "/stop";
        StopRecordResp stopRecordResp = new StopRecordResp();
        String json = "{\n" +
                "  \"cname\": \"httpClient\",\n" +
                "  \"uid\": \"1234567\",  \n" +
                "  \"clientRequest\":{\n" +
                "      \"async_stop\": false   \n" +
                "  }\n" +
                "}";
        try {
            String resp = HttpUtil.doPostWithHead(json, url, agoraService.getAuthorization());
            stopRecordResp = JSON.parseObject(resp, StopRecordResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BaseResp();
    }

    @ApiOperation("结束录制测试")
    @PostMapping("/stopRecord")
    public StopRecordResp stopRecord(@RequestBody StopRecordReq req) {
        return agoraService.stopRecord(req);
    }

    @ApiOperation("查询录制")
    @PostMapping("/queryRecord")
    public QueryRecordResp queryRecord(@RequestBody QueryRecordReq req) {
        return agoraService.queryRecord(req);
    }

    @ApiOperation("指定项目录制服务器ip")
    @GetMapping("/editRecordConfigIp")
    public ProjectDTO editRecordConfigIp(@RequestParam("id") String id, @RequestParam("recordingServer") String recordingServer) {
        return agoraService.editRecordConfigIp(id, recordingServer);
    }

    @ApiOperation("合伙人排行榜奖励")
    @GetMapping("/rankReward")
    public void rankReward(@RequestParam("type") Byte type) {
        userService.rankReward(type);
    }

    @ApiOperation("测试订阅物流")
    @GetMapping("/subscribeMessage")
    public BaseResp subscribeMessage() {
        try {
            String yto = logisticsService.subscribeMessage("YTO", "13");
            PushLogisticsResp pushLogisticsResp = JSON.parseObject(yto, PushLogisticsResp.class);
            if (!pushLogisticsResp.getSuccess()) {
                return new BaseResp(ResultCode.SUBSCRIBE_MESSAGE_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BaseResp();
    }

    @ApiOperation("测试推送")
    @GetMapping("/sendPushToPerson")
    public BaseResp sendPushToPerson(@RequestParam("message") String message, @RequestParam("registerId") String registerId) {
        jpushService.sendPushToPerson(message, registerId, "促销活动", null);
        return new BaseResp();
    }

    @ApiOperation("测试广播推送")
    @GetMapping("/sendPushToAll")
    public BaseResp sendPushToAll(@RequestParam("message") String message) {
        jpushService.sendPushToAll(message, "推送消息", null);
        return new BaseResp();
    }

    @ApiOperation("测试别名推送")
    @GetMapping("/sendPushToAlias")
    public BaseResp sendPushToAlias(@RequestParam("message") String message, @RequestParam("alias") String alias) {
        List<String> aliasList = new ArrayList<>();
        aliasList.add(alias);
        jpushService.sendPushToAlias(message, aliasList, "推送消息", null);
        return new BaseResp();
    }

    @ApiOperation("测试标签推送")
    @GetMapping("/sendPushToTags")
    public BaseResp sendPushToTags(@RequestParam("message") String message, @RequestParam("tag") String tag) {
        List<String> tags = new ArrayList<>();
        tags.add(tag);
        jpushService.sendPushToTags(message, tags, "推送消息", null);
        return new BaseResp();
    }

    @ApiOperation("测试发放沉淀分红")
    @GetMapping("/rewardDividendPrecipitation")
    public BaseResp rewardDividendPrecipitation() {
        commissionService.rewardDividendPrecipitation();
        return new BaseResp();
    }

    @ApiOperation("测试发放活动补贴")
    @GetMapping("/rewardMarketSubsidy")
    public BaseResp rewardMarketSubsidy() {
        commissionService.rewardMarketSubsidy();
        return new BaseResp();
    }

    @ApiOperation("测试发放联合创始人分红")
    @GetMapping("/rewardDirectorCommission")
    public BaseResp rewardDirectorCommission() {
        commissionService.rewardDirectorCommission();
        return new BaseResp();
    }

    @ApiOperation("测试发放分公司分红")
    @GetMapping("/rewardShareholderPrecipitation")
    public BaseResp rewardShareholderPrecipitation() {
        commissionService.rewardShareholderPrecipitation();
        return new BaseResp();
    }

    @ApiOperation("补发")
    @GetMapping("/hipoCommission")
    public BaseResp hipoCommission() {
        Orders orders = ordersMapper.selectByPrimaryKey(11599L);
        Shop shop = shopMapper.selectByPrimaryKey(orders.getShopId());

        if (orders.getTotalPayAmount().compareTo(BigDecimal.ZERO) > 0) {
            // 每个订单里最多只能有1个商品

            // 立即发放商品销售收入给商户
            Tenant tenant = tenantMapper.selectByPrimaryKey(shop.getId());
            tenantFlowMapper.insert(TenantFlow.builder()
                    .amount(orders.getTotalTenantAmount())
                    .tradeType(TenantTradeTypeEnum.PRODUCT.getTradeType())
                    .type(TenantTradeTypeEnum.PRODUCT.getType())
                    .point(tenant.getPoint().add(orders.getTotalTenantAmount()))
                    .relateId(orders.getId())
                    .remark("黑科技智能健身衣Hipo会员")
                    .createdAt(new Date())
                    .tenantId(tenant.getId())
                    .build());
            tenantMapper.updatePointById(tenant.getPoint().add(orders.getTotalTenantAmount()), tenant.getId());
            financeService.createFreezeAmount(orders, orders.getTotalTenantAmount(), FreezeTypeEnum.ORDERS.getType());
        }
        return new BaseResp();
    }

    @ApiOperation("测试免单失败")
    @GetMapping("/rewardQueueExchange")
    public BaseResp rewardQueueExchange() {
        quartzService.rewardQueueExchange(18934L);
        return new BaseResp();
    }

    @ApiOperation("测试发放福利补贴")
    @GetMapping("/rewardWelfare")
    public BaseResp rewardWelfare() {
        commissionService.rewardWelfare();
        return new BaseResp();
    }

    @ApiOperation("立即将冻结到期的发放掉")
    @GetMapping("/userCommissionList")
    public BaseResp userCommissionList() {
        int count = 0;
        List<UserCommission> userCommissionList = userCommissionMapper.findAllByStatusAndFreezeTime(UserCommissionStatusEnum.FREEZE.getStatus(), new Date());

        if (!com.alibaba.excel.util.CollectionUtils.isEmpty(userCommissionList)) {
            userCommissionList.stream().forEach(item -> {
                // 发放佣金
                commissionService.issueUserCommission(item);
            });

            count = userCommissionList.size();
        }
        return new BaseResp();
    }

    @ApiOperation("补发一单合伙人佣金")
    @GetMapping("/addOneCommission")
    public BaseResp addOneCommission() {
        // 设置冻结时间
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DATE, 7);
//
//        OrderSku item = orderSkuMapper.selectByPrimaryKey(628L);
//        Map<String, String> config = daoService.getHipoConfigMap();
//        // 上级合伙人得15%的直推佣金
//        Identity identity = identityMapper.findOneByUserId(42122L);
//        BigDecimal commission = item.getPayAmount().multiply(new BigDecimal(config.get(HipoConfigEnum.PARTNER_COMMISSION_RATE.getConfig()))).setScale(2, BigDecimal.ROUND_HALF_UP);
//        userCommissionMapper.insert(build(identity.getUserId(), item.getUserId(), commission, UserCommissionTypeEnum.PARTNER_SHARE_COMMISSION, calendar, item.getPayAmount(), IdentityTypeEnum.PARTNER.getType(), item.getId(), item.getProductName(), IdentityTypeEnum.MEMBER.getType()));
        return new BaseResp();
    }
}
